package com.qianbei.user.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.BaseFragment;
import com.qianbei.common.init.GlobalConfig;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.user.BindPhoneActivity;
import com.qianbei.user.ChangeUserActivity;
import com.qianbei.user.model.UserMode;
import com.qianbei.user.regist.RegisterFragment;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.Log;

import java.util.Map;

public class Login_regist_activity extends BaseActivity {

	private BaseFragment mLoginFragment;
	private BaseFragment mRegistFragment;

	private Button mWeChatLoginBtn;
	private Button mWeiBoLoginBtn;

	private UMShareAPI mShareAPI;
	private String mAccessToken;
	private String mRefreshToken;
	private String mOauthUid;

	private UserMode mUserMode;

	private boolean isLogin=true;
	private  Login_regist_topFragment title;

	private String mWeChatInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLoginFragment = new LoginFragment();
		mRegistFragment = new RegisterFragment();
		setContentView(R.layout.login_regist_activit);

		setTitle("登录注册");

		mWeChatInfo = getIntent().getStringExtra(ConstantValue.WE_CHAT_INFO_KEY);

		Bundle bundle = new Bundle();
		bundle.putString(ConstantValue.WE_CHAT_INFO_KEY,mWeChatInfo);
		mLoginFragment.setArguments(bundle);

		mWeChatLoginBtn = (Button) findViewById(R.id.we_chat_btn);
		mWeiBoLoginBtn = (Button) findViewById(R.id.wei_bo_btn);
		mWeChatLoginBtn.setOnClickListener(this);
		mWeiBoLoginBtn.setOnClickListener(this);

		mShareAPI = UMShareAPI.get(this);
		title = (Login_regist_topFragment)getSupportFragmentManager().findFragmentById(R.id.regist_login);
		isLogin=getIntent().getBooleanExtra(ConstantValue.SELECT_TAB_KEY,true);

		if(isLogin){
			title.setUnSelcet();
			showFragment(mLoginFragment,  R.id.lr_container);
		}else {
			title.setSelcet();
			showFragment(mRegistFragment,  R.id.lr_container);
		}
	}

	@Override
	public void fClick(int id) {
		super.fClick(id);
		switch (id) {
		case R.id.shop_button:
			showFragment(mRegistFragment,  R.id.lr_container);
			break;
		case R.id.food_button:
			showFragment(mLoginFragment,  R.id.lr_container);
			break;
		}

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		SHARE_MEDIA platform = null;
		switch (v.getId()){
			case R.id.we_chat_btn:
				mWeChatLoginBtn.setClickable(false);
				platform = SHARE_MEDIA.WEIXIN;
				break;
			case R.id.wei_bo_btn:
				mWeiBoLoginBtn.setClickable(false);
//				Config.REDIRECT_URL = BuildConfig.REDIRECT_URL;
				platform = SHARE_MEDIA.SINA;
				break;
		}

		mShareAPI.doOauthVerify(this, platform, umAuthListener);
	}


	private UMAuthListener umAuthListener = new UMAuthListener() {
		@Override
		public void onStart(SHARE_MEDIA share_media) {

		}

		@Override
		public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
			if (map!=null){
				Log.d("jiao","getting data "+map.toString());
				mAccessToken = map.get("access_token");
				mRefreshToken = map.get("refresh_token");


				if (share_media == SHARE_MEDIA.SINA){
					mOauthUid = map.get("uid");
				}else{
					mOauthUid = map.get("openid");
				}


				mShareAPI.getPlatformInfo(Login_regist_activity.this, share_media, platformInfoListener);

			}else{
				new MsgAlert().show(R.string.authorization_failed);
			}
		}

		@Override
		public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

		}

		@Override
		public void onCancel(SHARE_MEDIA share_media, int i) {
		}
	};


	private UMAuthListener platformInfoListener = new UMAuthListener() {

		@Override
		public void onStart(SHARE_MEDIA share_media) {

		}

		@Override
		public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
			if (map!=null){
				Log.d("jiao","getting info data "+map.toString());
				registRequest(share_media,map);
			}else{
				new MsgAlert().show(R.string.authorization_failed);
			}
		}

		@Override
		public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
			new MsgAlert().show(R.string.authorization_failed);
		}

		@Override
		public void onCancel(SHARE_MEDIA share_media, int i) {
			Log.d("onCancel info ");
		}
	};


	/**
	 * 根据第三方的登录信息 注册用户
	 *
	 * @param share_media
	 * @param map
     */
	public void registRequest(SHARE_MEDIA share_media,Map<String,String> map){

		String oauthFrom = "wb"; // 第三方登录来源，wb、qq、wx
		String oauthUnuid = "";
		String oauthNickName = "";
		String oauthFace = "";

		if (SHARE_MEDIA.SINA == share_media){
			oauthFrom = "wb";
			JSONObject jsonObject = JSON.parseObject(map.get("result"));
			oauthNickName = jsonObject.getString("name");
			oauthFace = jsonObject.getString("profile_image_url");
		}else if (SHARE_MEDIA.WEIXIN == share_media){
			oauthFrom = "wx";
			oauthUnuid = map.get("unionid");
			oauthNickName = map.get("nickname");
			oauthFace = map.get("headimgurl");
		}


		ServerControl sc = new ServerControl(OAUTH_SIGNIN_URL,
				"oauth_from", oauthFrom,		// 第三方返回的openid
				"oauth_uid", mOauthUid,			// 第三方返回的openid
				"access_token", mAccessToken,	// 第三方返回的授权token
				"refresh_token", mRefreshToken, // 第三方刷新token
				"oauth_nickname", oauthNickName,// 第三方昵称
				"oauth_face", oauthFace,	    // 第三方头像
				"oauth_unuid",oauthUnuid		// 微信登录必须，跨应用的唯一id
				);

		sc.serverListener = new ServerControl.ServerListener() {

			@Override
			public void serverFinish(ServerResult sr) {
				if (sr.isContinue) {
					if (sr.bodyData != null){

						mUserMode = JSON.parseObject(
								sr.bodyData.optString("userInfo").toString(),
								UserMode.class);

						if (sr.bodyData.optBoolean("has_phone")){//如果已绑定则保存信息，开启服务
							doAction();
						}else{ //跳转到绑定手机号页面
							startActivityForResult(new Intent(Login_regist_activity.this,
									BindPhoneActivity.class),1);
						}
					}
				}
			}
		};

		new ProgressDialog(mContext).startControl(sc,getString(R.string.login));
	}

	/**
	 *
	 * 下一步操作
	 */
	public void doAction(){


		if (!TextUtils.isEmpty(mUserMode.user_id)) {
			saveLoginInfo(mUserMode);
		}

		// 判断第一次登录显示 页面 登录依据
//		if (SetData.getLoginshow(mUserMode.user_id)) {
//			ActivityManagers.getInstance().finishActivity(GuideActivity.class);
//			Intent intent = new Intent(Login_regist_activity.this,LogginShowActivity.class);
//			intent.putExtra("targetClass", "");
//			startActivity(intent);
//
//			SetData.setLoginshow(false, mUserMode.user_id);
//		} else {
			try {
				Class<?> targetClass = Class.forName(
						getIntent().getStringExtra("targetClass"));
				Intent intent = new Intent(mContext, targetClass);
				startActivity(intent);

			} catch (Exception e) {
				e.printStackTrace();
			}
//		}


		finish();
	}


	/**
	 * 保存用户信息
	 *
	 * @param bean
     */
	private void saveLoginInfo(UserMode bean) // 存储注册信息
	{

//		JpushManager.getIJpushManager().setAlias(bean.easemob_name);
//		JpushManager.getIJpushManager().setTag("jiemianmaster_register_user");

		SetData.setUserID(bean.user_id);
		SetData.setFace(bean.profile_image_url);
		SetData.setUserName(bean.name);
		SetData.sethxID(bean.easemob_name);
		SetData.sethxpass(bean.random_string);
		SetData.setUserType(bean.type);
		SetData.setCity(bean.city);
		SetData.setCountry(bean.country);
		SetData.setCareer(bean.identity);
		SetData.setIntroduction(bean.career);
		SetData.setNickName(bean.nickname);
		SetData.setUserPhone(bean.phone_number);

		GlobalConfig config = GlobalConfig.getInstance();

		if (bean.type.equals("true")) {// true 是前辈
			config.identity = "1";
			SetData.setIdentity("1");
		} else {
			SetData.setIdentity("0");
			config.identity = "0";
		}


		config.userID = bean.user_id;
		config.iconURl = bean.profile_image_url;
		config.userName = bean.name;
		config.hxID = bean.easemob_name;

		// HuanxinHelper.getInstance().login();
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK){ //绑定手机成功后回调
			startActivityForResult(new Intent(this,ChangeUserActivity.class),2);
		}else if (requestCode == 2 && resultCode == RESULT_OK){ //完善用户资料后回调
			getUerInfo();
		}else{ //友盟回调
			mShareAPI.onActivityResult(requestCode,resultCode,data);
		}
	}


	/**
	 * 获取用户资料
	 */
	private void getUerInfo() {
		ServerControl sc = new ServerControl(Request.Method.GET, user_info + "?");
		sc.serverListener = new ServerControl.ServerListener() {
			@Override
			public void serverFinish(ServerResult sr) {

				if (sr.isContinue) {
					mUserMode = JSON.parseObject(
							sr.bodyData.optJSONObject("userInfo").toString(),
							UserMode.class);
					doAction();
				}
			}
		};
//		sc.startVolley();
		 new ProgressDialog(mContext).startControl(sc);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mWeiBoLoginBtn.setClickable(true);
		mWeChatLoginBtn.setClickable(true);
	}
}
